<template>
  <div class="process-properties-panel">
    <!-- 节点属性配置 -->
    <div v-if="selectedNode" class="node-properties">
      <div class="property-section">
        <h4>基本信息</h4>
        <el-form label-width="80px" size="small">
          <el-form-item label="节点名称">
            <el-input
              :model-value="selectedNode.name"
              @input="updateNodeProperty('name', $event)"
              placeholder="请输入节点名称"
            />
          </el-form-item>
          
          <el-form-item label="节点ID">
            <el-input
              :model-value="selectedNode.id"
              disabled
              placeholder="系统自动生成"
            />
          </el-form-item>
          
          <el-form-item label="节点类型">
            <el-tag :type="getNodeTypeTagType(selectedNode.type)">
              {{ getNodeTypeText(selectedNode.type) }}
            </el-tag>
          </el-form-item>
          
          <el-form-item label="节点描述">
            <el-input
              :model-value="selectedNode.description || ''"
              @input="updateNodeProperty('description', $event)"
              type="textarea"
              :rows="2"
              placeholder="请输入节点描述（可选）"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 审批节点特有配置 -->
      <div v-if="selectedNode.type === 'APPROVAL'" class="property-section">
        <h4>审批配置</h4>
        <el-form label-width="90px" size="small">
          <el-form-item label="处理人类型">
            <el-select
              :model-value="(selectedNode as ApprovalNode).assigneeType || 'FIXED'"
              @change="handleAssigneeTypeChange"
              style="width: 100%"
            >
              <el-option label="固定用户" value="FIXED">
                <div class="assignee-type-option">
                  <span>固定用户</span>
                  <el-text size="small" type="info">选择系统用户</el-text>
                </div>
              </el-option>
              <el-option label="动态人员" value="DYNAMIC">
                <div class="assignee-type-option">
                  <span>动态人员</span>
                  <el-text size="small" type="info">从流程变量获取</el-text>
                </div>
              </el-option>
              <!-- <el-option label="角色" value="ROLE" /> -->
              <!-- <el-option label="表达式" value="EXPRESSION" /> -->
            </el-select>
          </el-form-item>
          
          <!-- 固定用户模式 -->
          <el-form-item 
            v-if="(selectedNode as ApprovalNode).assigneeType === 'FIXED' || !(selectedNode as ApprovalNode).assigneeType"
            label="处理人"
          >
            <el-select
              :model-value="getAssigneeValue((selectedNode as ApprovalNode).assignee)"
              @change="updateNodeProperty('assignee', $event)"
              placeholder="请选择处理人"
              style="width: 100%"
              filterable
              remote
              :remote-method="searchUsers"
              :loading="userLoading"
              clearable
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.realName || user.username"
                :value="user.id"
              >
                <div class="user-option">
                  <span class="user-name">{{ user.realName || user.username }}</span>
                  <span class="user-info">{{ user.email }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 动态人员模式 - 从流程变量选择 -->
          <el-form-item 
            v-if="(selectedNode as ApprovalNode).assigneeType === 'DYNAMIC'"
            label="人员变量"
          >
            <el-select
              :model-value="(selectedNode as ApprovalNode).assignee"
              @change="updateNodeProperty('assignee', $event)"
              placeholder="选择人员字段变量"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="variable in getUserVariables()"
                :key="variable.name"
                :label="variable.label || variable.name"
                :value="variable.name"
              >
                <div class="variable-option">
                  <span class="variable-name">{{ variable.label || variable.name }}</span>
                  <el-tag size="small" type="warning">{{ variable.type }}</el-tag>
                </div>
              </el-option>
            </el-select>
            <el-text size="small" type="info" style="margin-top: 4px; display: block;">
              从流程变量中获取审批人，变量值应为用户ID
            </el-text>
          </el-form-item>
          
          <el-form-item label="关联表单">
            <el-input
              :model-value="(selectedNode as ApprovalNode).formKey || ''"
              @input="updateNodeProperty('formKey', $event)"
              placeholder="表单标识（可选）"
            />
          </el-form-item>
          
          <el-form-item label="允许驳回">
            <el-switch
              :model-value="(selectedNode as ApprovalNode).allowReject"
              @change="updateNodeProperty('allowReject', $event)"
            />
          </el-form-item>
          
          <el-form-item label="节点描述">
            <el-input
              :model-value="(selectedNode as ApprovalNode).description || ''"
              @input="updateNodeProperty('description', $event)"
              type="textarea"
              :rows="2"
              placeholder="请输入节点描述（可选）"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 条件分支节点特有配置 -->
      <div v-if="selectedNode.type === 'CONDITIONAL_BRANCH'" class="property-section">
        <h4>分支配置</h4>
        <el-form label-width="80px" size="small">
          <el-form-item label="默认分支">
            <el-select
              :model-value="(selectedNode as ConditionalBranchNode).defaultFlow || ''"
              @change="updateNodeProperty('defaultFlow', $event)"
              placeholder="选择默认分支"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="flow in getOutgoingFlows(selectedNode.id)"
                :key="flow.id"
                :label="flow.name || `连接到${getTargetNodeName(flow.to)}`"
                :value="flow.id"
              />
            </el-select>
            <el-text size="small" type="info" style="margin-top: 4px; display: block;">
              当所有条件都不满足时，执行默认分支
            </el-text>
          </el-form-item>
          
          <el-form-item label="节点描述">
            <el-input
              :model-value="(selectedNode as ConditionalBranchNode).description || ''"
              @input="updateNodeProperty('description', $event)"
              type="textarea"
              :rows="2"
              placeholder="请输入节点描述（可选）"
            />
          </el-form-item>
        </el-form>
        
        <div class="flows-config">
          <h5>输出连接配置</h5>
          <div v-if="getOutgoingFlows(selectedNode.id).length === 0" class="no-flows">
            <el-empty description="暂无输出连接" :image-size="60" />
          </div>
          <div v-else>
            <div
              v-for="flow in getOutgoingFlows(selectedNode.id)"
              :key="flow.id"
              class="flow-config-item"
            >
              <div class="flow-info">
                <span class="flow-label">→ {{ getTargetNodeName(flow.to) }}</span>
                <el-button
                  size="small"
                  type="danger"
                  text
                  @click="deleteFlow(flow.id)"
                >
                  删除
                </el-button>
              </div>
              <ConditionBuilder
                :model-value="flow.condition || ''"
                @update:model-value="updateFlowProperty(flow.id, 'condition', $event)"
                :process-variables="process.variables || []"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 抄送节点特有配置 -->
      <div v-if="selectedNode.type === 'CC'" class="property-section">
        <h4>抄送配置</h4>
        <el-form label-width="90px" size="small">
          <el-form-item label="抄送人类型">
            <el-select
              :model-value="(selectedNode as any).assigneeType || 'FIXED'"
              @change="handleCcAssigneeTypeChange"
              style="width: 100%"
            >
              <el-option label="固定用户" value="FIXED">
                <div class="assignee-type-option">
                  <span>固定用户</span>
                  <el-text size="small" type="info">选择系统用户</el-text>
                </div>
              </el-option>
              <el-option label="动态人员" value="DYNAMIC">
                <div class="assignee-type-option">
                  <span>动态人员</span>
                  <el-text size="small" type="info">从流程变量获取</el-text>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 固定用户模式 -->
          <el-form-item 
            v-if="(selectedNode as any).assigneeType === 'FIXED' || !(selectedNode as any).assigneeType"
            label="抄送人"
          >
            <el-select
              :model-value="getAssigneeValue((selectedNode as any).assignee)"
              @change="updateNodeProperty('assignee', $event)"
              placeholder="请选择抄送人"
              style="width: 100%"
              filterable
              remote
              :remote-method="searchUsers"
              :loading="userLoading"
              clearable
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.realName || user.username"
                :value="user.id"
              >
                <div class="user-option">
                  <span class="user-name">{{ user.realName || user.username }}</span>
                  <span class="user-info">{{ user.email }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 动态人员模式 -->
          <el-form-item 
            v-if="(selectedNode as any).assigneeType === 'DYNAMIC'"
            label="人员变量"
          >
            <el-select
              :model-value="(selectedNode as any).assignee"
              @change="updateNodeProperty('assignee', $event)"
              placeholder="选择人员字段变量"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="variable in getUserVariables()"
                :key="variable.name"
                :label="variable.label || variable.name"
                :value="variable.name"
              >
                <div class="variable-option">
                  <span class="variable-name">{{ variable.label || variable.name }}</span>
                  <el-tag size="small" type="warning">{{ variable.type }}</el-tag>
                </div>
              </el-option>
            </el-select>
            <el-text size="small" type="info" style="margin-top: 4px; display: block;">
              从流程变量中获取抄送人，变量值应为用户ID
            </el-text>
          </el-form-item>
          
          <el-form-item label="关联表单">
            <el-input
              :model-value="(selectedNode as any).formKey || ''"
              @input="updateNodeProperty('formKey', $event)"
              placeholder="表单标识（可选）"
            />
          </el-form-item>
          
          <el-form-item label="通知方式">
            <el-select
              :model-value="(selectedNode as any).notifyType || 'SYSTEM'"
              @change="updateNodeProperty('notifyType', $event)"
              style="width: 100%"
            >
              <el-option label="系统通知" value="SYSTEM" />
              <el-option label="邮件通知" value="EMAIL" />
              <el-option label="短信通知" value="SMS" />
              <el-option label="全部通知" value="ALL" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="必须查看">
            <el-switch
              :model-value="(selectedNode as any).requireRead || false"
              @change="updateNodeProperty('requireRead', $event)"
            />
            <el-text size="small" type="info" style="margin-left: 8px; display: block; margin-top: 4px;">
              开启后，抄送人必须查看后才能继续流程
            </el-text>
          </el-form-item>
          
          <el-form-item label="节点描述">
            <el-input
              :model-value="(selectedNode as any).description || ''"
              @input="updateNodeProperty('description', $event)"
              type="textarea"
              :rows="2"
              placeholder="请输入节点描述（可选）"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 并行节点特有配置 -->
      <div v-if="selectedNode.type === 'PARALLEL'" class="property-section">
        <h4>并行配置</h4>
        <el-form label-width="90px" size="small">
          <el-form-item label="执行策略">
            <el-select
              :model-value="(selectedNode as any).strategy || 'ALL'"
              @change="updateNodeProperty('strategy', $event)"
              style="width: 100%"
            >
              <el-option label="全部完成" value="ALL">
                <div class="assignee-type-option">
                  <span>全部完成</span>
                  <el-text size="small" type="info">所有分支都完成后才继续</el-text>
                </div>
              </el-option>
              <el-option label="任意完成" value="ANY">
                <div class="assignee-type-option">
                  <span>任意完成</span>
                  <el-text size="small" type="info">任意一个分支完成即可继续</el-text>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="节点描述">
            <el-input
              :model-value="(selectedNode as any).description || ''"
              @input="updateNodeProperty('description', $event)"
              type="textarea"
              :rows="2"
              placeholder="请输入节点描述（可选）"
            />
          </el-form-item>
        </el-form>
        
        <div class="parallel-branches">
          <div class="branches-header">
            <h5>并行分支</h5>
            <el-button 
              type="primary" 
              size="small" 
              @click="addParallelBranch"
              :disabled="(selectedNode as any).branches?.length >= 10"
            >
              <el-icon><Plus /></el-icon>
              添加分支
            </el-button>
          </div>
          
          <div
            v-for="(branch, index) in (selectedNode as any).branches || []"
            :key="branch.id"
            class="branch-item"
          >
            <div class="branch-header">
              <span class="branch-title">分支 {{ index + 1 }}</span>
              <el-button
                size="small"
                type="danger"
                text
                @click="removeParallelBranch(branch.id)"
                :disabled="(selectedNode as any).branches?.length <= 2"
              >
                删除
              </el-button>
            </div>
            <el-form label-width="80px" size="small" style="margin-top: 8px;">
              <el-form-item label="分支名称">
                <el-input
                  :model-value="branch.name"
                  @input="updateParallelBranchName(branch.id, $event)"
                  placeholder="请输入分支名称"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="分支描述">
                <el-input
                  :model-value="branch.description || ''"
                  @input="updateParallelBranchDescription(branch.id, $event)"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入分支描述（可选）"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="分支条件">
                <ConditionBuilder
                  :model-value="branch.condition || ''"
                  @update:model-value="updateParallelBranchCondition(branch.id, $event)"
                  :process-variables="process.variables || []"
                />
                <el-text size="small" type="info" style="margin-top: 4px; display: block;">
                  可选：设置分支执行条件
                </el-text>
              </el-form-item>
            </el-form>
          </div>
          
          <div v-if="!(selectedNode as any).branches || (selectedNode as any).branches.length === 0" class="no-branches">
            <el-empty description="暂无分支，请添加分支" :image-size="60" />
          </div>
        </div>
      </div>

      <!-- 位置信息 -->
      <div class="property-section">
        <h4>位置信息</h4>
        <el-form label-width="80px" size="small">
          <el-form-item label="X坐标">
            <el-input-number
              :model-value="selectedNode.position.x"
              @change="updateNodePosition('x', $event)"
              :min="50"
              :max="1600"
              size="small"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="Y坐标">
            <el-input-number
              :model-value="selectedNode.position.y"
              @change="updateNodePosition('y', $event)"
              :min="50"
              :max="1800"
              size="small"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 流程基本信息和变量配置 -->
    <div v-else class="process-config">
      <!-- 流程基本信息 -->
      <div class="property-section">
        <h4>流程信息</h4>
        <el-form label-width="80px" size="small">
          <el-form-item label="流程名称">
            <el-input
              :model-value="process.name"
              @input="updateProcessProperty('name', $event)"
              placeholder="请输入流程名称"
            />
          </el-form-item>
          
          <el-form-item label="流程标识">
            <el-input
              :model-value="process.key"
              @input="updateProcessProperty('key', $event)"
              placeholder="流程标识（英文）"
            />
          </el-form-item>
          
          <el-form-item label="流程描述">
            <el-input
              :model-value="process.description || ''"
              @input="updateProcessProperty('description', $event)"
              type="textarea"
              :rows="3"
              placeholder="请输入流程描述"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作指南 -->
      <div class="property-section">
        <h4>操作指南</h4>
        <el-card class="operation-guide" shadow="never">
          <div class="guide-item">
            <el-icon class="guide-icon"><Mouse /></el-icon>
            <div class="guide-text">
              <div class="guide-title">添加节点</div>
              <div class="guide-desc">从左侧拖拽节点到画布</div>
            </div>
          </div>
          <div class="guide-item">
            <el-icon class="guide-icon"><Connection /></el-icon>
            <div class="guide-text">
              <div class="guide-title">创建连接</div>
              <div class="guide-desc">点击节点的输出点，再点击目标节点的输入点</div>
            </div>
          </div>
          <div class="guide-item">
            <el-icon class="guide-icon"><Setting /></el-icon>
            <div class="guide-text">
              <div class="guide-title">配置属性</div>
              <div class="guide-desc">选中节点或连接线，在此面板配置属性</div>
            </div>
          </div>
          <div class="guide-item">
            <el-icon class="guide-icon"><Delete /></el-icon>
            <div class="guide-text">
              <div class="guide-title">删除元素</div>
              <div class="guide-desc">右键连接线删除，或使用属性面板删除按钮</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 流程变量配置 (始终显示) -->
    <div class="process-variables">
      <div class="property-section">
        <h4>流程变量</h4>
        <div class="variables-list">
          <div v-if="!process.variables || process.variables.length === 0" class="no-variables">
            <el-empty description="暂无流程变量" :image-size="60" />
          </div>
          <div v-else>
            <div
              v-for="(variable, index) in process.variables"
              :key="variable.name"
              class="variable-item"
            >
              <div class="variable-info">
                <div class="variable-name">{{ variable.name }}</div>
                <div class="variable-details">
                  <el-tag size="small">{{ variable.type }}</el-tag>
                  <span class="variable-label">{{ variable.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <el-button
          type="primary"
          size="small"
          @click="showAddVariableDialog"
          style="width: 100%; margin-top: 12px"
        >
          <el-icon><Plus /></el-icon>
          添加变量
        </el-button>
      </div>
    </div>

    <!-- 添加变量对话框 -->
    <el-dialog
      v-model="addVariableDialogVisible"
      title="添加流程变量"
      width="500px"
    >
      <el-form
        ref="variableFormRef"
        :model="newVariable"
        :rules="variableFormRules"
        label-width="80px"
      >
        <el-form-item label="变量名" prop="name">
          <el-input
            v-model="newVariable.name"
            placeholder="变量名（英文）"
          />
        </el-form-item>
        <el-form-item label="显示名称" prop="label">
          <el-input
            v-model="newVariable.label"
            placeholder="变量的显示名称"
          />
        </el-form-item>
        <el-form-item label="数据类型" prop="type">
          <el-select
            v-model="newVariable.type"
            placeholder="选择数据类型"
            style="width: 100%"
          >
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="double" />
            <el-option label="整数" value="long" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="日期" value="date" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认值">
          <el-input
            v-model="newVariable.defaultValue"
            placeholder="默认值（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVariableDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addVariable">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, Mouse, Connection, Setting } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import ConditionBuilder from './ConditionBuilder.vue'
import type { 
  ProcessDefinition, 
  ProcessNode, 
  ProcessFlow, 
  ApprovalNode, 
  ConditionalBranchNode,
  ProcessVariable 
} from '@/stores/workflow/processDesigner'

// 用户相关类型定义
interface User {
  id: number
  username: string
  realName?: string
  email?: string
}

// Props
interface Props {
  selectedNode?: ProcessNode | null
  selectedFlow?: ProcessFlow | null
  process: ProcessDefinition
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'node-updated': [nodeId: string, updates: Partial<ProcessNode>]
  'flow-updated': [flowId: string, updates: Partial<ProcessFlow>]
  'flow-deleted': [flowId: string]
  'variable-added': [variable: ProcessVariable]
  'variable-deleted': [variableName: string]
  'process-updated': [updates: Partial<ProcessDefinition>]
}>()

// 响应式数据
const addVariableDialogVisible = ref(false)
const variableFormRef = ref()
const newVariable = ref<ProcessVariable>({
  name: '',
  type: 'string',
  label: '',
  defaultValue: ''
})

// 用户相关响应式数据
const userList = ref<User[]>([])
const userLoading = ref(false)
const allUsers = ref<User[]>([]) // 缓存所有用户

const variableFormRules = {
  name: [
    { required: true, message: '请输入变量名', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '变量名必须以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  label: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ]
}

// 计算属性
const selectedNode = computed(() => {
  // 当选中审批节点或抄送节点时，确保用户数据已加载
  if ((props.selectedNode?.type === 'APPROVAL' || props.selectedNode?.type === 'CC') && allUsers.value.length === 0) {
    loadAllUsers()
  }
  return props.selectedNode
})
const selectedFlow = computed(() => props.selectedFlow)
const process = computed(() => props.process)

// 方法
const getNodeTypeText = (type: string) => {
  const typeMap = {
    START: '开始节点',
    END: '结束节点',
    APPROVAL: '审批节点',
    CC: '抄送节点',
    CONDITIONAL_BRANCH: '条件分支',
    PARALLEL: '并行节点'
  }
  return typeMap[type as keyof typeof typeMap] || '未知节点'
}

const getNodeTypeTagType = (type: string) => {
  const typeMap = {
    START: 'success',
    END: 'danger',
    APPROVAL: 'primary',
    CC: 'info',
    CONDITIONAL_BRANCH: 'warning',
    PARALLEL: 'success'
  }
  return typeMap[type as keyof typeof typeMap] || 'info'
}

const getAssigneeTypePlaceholder = (type: string) => {
  const placeholderMap = {
    FIXED: '用户ID或用户名',
    ROLE: '角色标识',
    EXPRESSION: 'SpEL表达式，如：${currentUser.deptId}'
  }
  return placeholderMap[type as keyof typeof placeholderMap] || '请输入处理人'
}

const getNodeName = (nodeId: string) => {
  const node = process.value.nodes.find(n => n.id === nodeId)
  return node ? node.name : '未知节点'
}

const getTargetNodeName = (nodeId: string) => {
  const node = process.value.nodes.find(n => n.id === nodeId)
  return node ? node.name : '未知节点'
}

const getOutgoingFlows = (nodeId: string) => {
  return process.value.flows.filter(f => f.from === nodeId)
}

const getStartNodesCount = () => {
  return process.value.nodes.filter(n => n.type === 'START').length
}

const updateNodeProperty = (key: string, value: any) => {
  if (selectedNode.value) {
    const updates: any = { [key]: value }
    emit('node-updated', selectedNode.value.id, updates)
  }
}

// 处理审批人类型变更
const handleAssigneeTypeChange = (value: string) => {
  if (selectedNode.value) {
    const updates: any = { 
      assigneeType: value,
      assignee: undefined // 清空原有的处理人配置
    }
    emit('node-updated', selectedNode.value.id, updates)
  }
}

// 处理抄送人类型变更
const handleCcAssigneeTypeChange = (value: string) => {
  if (selectedNode.value) {
    const updates: any = { 
      assigneeType: value,
      assignee: undefined // 清空原有的抄送人配置
    }
    emit('node-updated', selectedNode.value.id, updates)
  }
}

// 添加并行分支
const addParallelBranch = () => {
  if (!selectedNode.value || selectedNode.value.type !== 'PARALLEL') return
  
  const branches = (selectedNode.value as any).branches || []
  if (branches.length >= 10) {
    ElMessage.warning('并行分支最多支持10个')
    return
  }
  
  const newBranch = {
    id: `branch_${Date.now()}`,
    name: `分支${branches.length + 1}`,
    description: '',
    nodes: [],
    condition: null
  }
  
  const updatedBranches = [...branches, newBranch]
  emit('node-updated', selectedNode.value.id, { branches: updatedBranches })
}

// 删除并行分支
const removeParallelBranch = (branchId: string) => {
  if (!selectedNode.value || selectedNode.value.type !== 'PARALLEL') return
  
  const branches = (selectedNode.value as any).branches || []
  const updatedBranches = branches.filter((b: any) => b.id !== branchId)
  
  if (updatedBranches.length < 2) {
    ElMessage.warning('并行节点至少需要两个分支')
    return
  }
  
  emit('node-updated', selectedNode.value.id, { branches: updatedBranches })
}

// 更新并行分支名称
const updateParallelBranchName = (branchId: string, name: string) => {
  if (!selectedNode.value || selectedNode.value.type !== 'PARALLEL') return
  
  const branches = (selectedNode.value as any).branches || []
  const updatedBranches = branches.map((b: any) => 
    b.id === branchId ? { ...b, name } : b
  )
  
  emit('node-updated', selectedNode.value.id, { branches: updatedBranches })
}

// 更新并行分支描述
const updateParallelBranchDescription = (branchId: string, description: string) => {
  if (!selectedNode.value || selectedNode.value.type !== 'PARALLEL') return
  
  const branches = (selectedNode.value as any).branches || []
  const updatedBranches = branches.map((b: any) => 
    b.id === branchId ? { ...b, description } : b
  )
  
  emit('node-updated', selectedNode.value.id, { branches: updatedBranches })
}

// 更新并行分支条件
const updateParallelBranchCondition = (branchId: string, condition: string) => {
  if (!selectedNode.value || selectedNode.value.type !== 'PARALLEL') return
  
  const branches = (selectedNode.value as any).branches || []
  const updatedBranches = branches.map((b: any) => 
    b.id === branchId ? { ...b, condition: condition || null } : b
  )
  
  emit('node-updated', selectedNode.value.id, { branches: updatedBranches })
}

// 获取可用作人员字段的流程变量
const getUserVariables = () => {
  if (!process.value.variables) {
    return []
  }
  
  // 返回所有变量（任何类型的变量都可能包含用户ID）
  // 如果要严格限制，可以只返回 string 或 number 类型的变量
  return process.value.variables.filter(v => 
    v.type === 'string' || v.type === 'number' || v.type === 'long'
  )
}

const updateNodePosition = (axis: 'x' | 'y', value: number) => {
  if (selectedNode.value) {
    const newPosition = { ...selectedNode.value.position, [axis]: value }
    emit('node-updated', selectedNode.value.id, { position: newPosition })
  }
}

const updateFlowProperty = (flowId: string, key: string, value: any) => {
  emit('flow-updated', flowId, { [key]: value })
}

const updateProcessProperty = (key: string, value: any) => {
  emit('process-updated', { [key]: value })
}

const deleteSelectedNode = async () => {
  if (!selectedNode.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除节点"${selectedNode.value.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 由父组件处理删除逻辑
    // emit('node-deleted', selectedNode.value.id)
  } catch (error) {
    // 用户取消
  }
}

const deleteSelectedFlow = async () => {
  if (!selectedFlow.value) return
  
  try {
    await ElMessageBox.confirm(
      '确定要删除此连接吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('flow-deleted', selectedFlow.value.id)
  } catch (error) {
    // 用户取消
  }
}

const deleteFlow = (flowId: string) => {
  emit('flow-deleted', flowId)
}

const showAddVariableDialog = () => {
  newVariable.value = {
    name: '',
    type: 'string',
    label: '',
    defaultValue: ''
  }
  addVariableDialogVisible.value = true
}

const addVariable = async () => {
  try {
    await variableFormRef.value?.validate()
    
    // 检查变量名是否已存在
    const existingVariable = process.value.variables?.find(v => v.name === newVariable.value.name)
    if (existingVariable) {
      ElMessage.error('变量名已存在')
      return
    }
    
    emit('variable-added', { ...newVariable.value })
    addVariableDialogVisible.value = false
    ElMessage.success('变量添加成功')
  } catch (error) {
    // 验证失败
  }
}

const deleteVariable = async (variableName: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除变量"${variableName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('variable-deleted', variableName)
    ElMessage.success('变量删除成功')
  } catch (error) {
    // 用户取消
  }
}

// 用户查询相关方法
const loadAllUsers = async () => {
  try {
    userLoading.value = true
    const result = await userApi.getEnabledUsers()
    
    allUsers.value = result.data || []
    userList.value = allUsers.value
  } catch (error) {
    console.error('加载用户列表出错:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    userLoading.value = false
  }
}

const searchUsers = async (query: string) => {
  if (!query) {
    userList.value = allUsers.value
    return
  }
  
  // 本地搜索（从缓存的用户列表中过滤）
  const filteredUsers = allUsers.value.filter(user => {
    const searchText = query.toLowerCase()
    return (
      (user.realName && user.realName.toLowerCase().includes(searchText)) ||
      user.username.toLowerCase().includes(searchText) ||
      (user.email && user.email.toLowerCase().includes(searchText))
    )
  })
  
  userList.value = filteredUsers
}

// 获取处理人值（确保类型匹配）
const getAssigneeValue = (assignee: string | number | undefined): number | undefined => {
  if (!assignee) {
    return undefined
  }
  
  // 如果是字符串，尝试转换为数字
  if (typeof assignee === 'string') {
    const numValue = parseInt(assignee)
    return isNaN(numValue) ? undefined : numValue
  }
  
  // 如果已经是数字，直接返回
  return typeof assignee === 'number' ? assignee : undefined
}

// 组件挂载时加载用户列表
onMounted(() => {
  loadAllUsers()
})
</script>

<style scoped lang="scss">
.process-properties-panel {
  padding: 16px;
  // 移除 height: 100% 和 overflow-y，让父容器控制滚动
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.property-section {
  margin-bottom: 24px;
  
  h4 {
    margin: 0 0 12px 0;
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary, #1f2937);
    border-bottom: 1px solid var(--border-color, #e5e7eb);
    padding-bottom: 8px;
    background: transparent;
  }
  
  h5 {
    margin: 12px 0 8px 0;
    font-size: 13px;
    color: var(--text-secondary, #6b7280);
    background: transparent;
  }
}

.flows-config {
  .no-flows {
    text-align: center;
    padding: 20px 0;
  }
  
  .flow-config-item {
    margin-bottom: 12px;
    padding: 8px;
    border: 1px solid var(--border-color, #e5e7eb);
    border-radius: 4px;
    background: var(--bg-tertiary, #f1f5f9);
    
    .flow-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .flow-label {
        font-size: 12px;
        color: var(--text-secondary, #6b7280);
      }
    }
  }
}

.condition-help {
  margin-top: 4px;
}

.property-actions {
  margin-top: 20px;
  text-align: center;
}

.variables-list {
  .no-variables {
    text-align: center;
    padding: 20px 0;
  }
  
  .variable-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border: 1px solid var(--border-color, #e5e7eb);
    border-radius: 4px;
    margin-bottom: 8px;
    background: var(--bg-card, #ffffff);
    
    .variable-info {
      flex: 1;
      
      .variable-name {
        font-weight: 500;
        color: var(--text-primary, #1f2937);
        margin-bottom: 4px;
      }
      
      .variable-details {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .variable-label {
          font-size: 12px;
          color: var(--text-secondary, #6b7280);
        }
      }
    }
  }
}

.operation-guide {
  background: var(--bg-tertiary, #f1f5f9);
  border: 1px solid var(--border-color, #e5e7eb);
  
  .guide-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .guide-icon {
      font-size: 16px;
      color: var(--primary-color, #6366f1);
      margin-right: 8px;
      margin-top: 2px;
    }
    
    .guide-text {
      flex: 1;
      
      .guide-title {
        font-size: 13px;
        font-weight: 500;
        color: var(--text-primary, #1f2937);
        margin-bottom: 2px;
      }
      
      .guide-desc {
        font-size: 11px;
        color: var(--text-secondary, #6b7280);
        line-height: 1.4;
      }
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-size: 12px;
  color: var(--text-secondary, #6b7280);
}

:deep(.el-input), :deep(.el-select) {
  .el-input__inner, .el-select__wrapper {
    font-size: 12px;
  }
}

:deep(.el-empty__description) {
  font-size: 12px;
}

// 用户选项样式
.user-option {
  display: flex;
  flex-direction: column;
  
  .user-name {
    font-size: 14px;
    color: var(--text-primary, #1f2937);
    font-weight: 500;
  }
  
  .user-info {
    font-size: 12px;
    color: var(--text-secondary, #6b7280);
    margin-top: 2px;
  }
}

// 处理人类型选项样式
.assignee-type-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  
  span {
    font-size: 13px;
    color: var(--text-primary, #1f2937);
  }
  
  .el-text {
    font-size: 11px;
  }
}

// 并行分支配置样式
.parallel-branches {
  margin-top: 12px;
  
  .branches-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    h5 {
      font-size: 13px;
      font-weight: 600;
      color: var(--text-primary, #1f2937);
      margin: 0;
    }
  }
  
  .branch-item {
    border: 1px solid var(--border-color, #e5e7eb);
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 12px;
    background: var(--bg-tertiary, #f1f5f9);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .branch-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .branch-title {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-primary, #1f2937);
      }
    }
  }
  
  .no-branches {
    text-align: center;
    padding: 20px 0;
  }
}

// 变量选项样式（用于动态人员）
.variable-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .variable-name {
    flex: 1;
    font-size: 13px;
    color: var(--text-primary, #1f2937);
  }
  
  .el-tag {
    margin-left: 8px;
  }
}
</style>
